package tables

import (
	"errors"
	"gorm.io/gorm"
	"peilian-api/app/global/variable"
)

// Profession 专业信息表，分为3个层级，对题目/图库等进行分类

type Profession struct {
	Model
	Tier       string `gorm:"index;type:varchar(15);not null;comment:层级,first/second/third" json:"tier"`
	Name       string `gorm:"type:varchar(255);not null;comment:构成要素名称" json:"name"`
	BelongToID *uint  `gorm:"index;comment:父级构成要素ID" json:"belong_to_id"`
}

func (Profession) TableName() string {
	return "profession"
}

func GetProfessionById(id uint) (Profession, error) {
	var p Profession
	d := variable.DB.MySQL.Model(&Profession{}).Where("id = ?", id).First(&p)
	if d.Error != nil {
		if errors.Is(d.Error, gorm.ErrRecordNotFound) {
			return p, nil
		}
		return p, d.Error
	}
	return p, nil
}

func GetProfessionChildIds(id uint) ([]uint, error) {
	var result = []uint{id}

	var belongs = []uint{id}
	for len(belongs) > 0 {
		var p []Profession
		d := variable.DB.MySQL.Model(&Profession{}).Where("belong_to_id in ?", belongs).Find(&p)
		if d.Error != nil {
			if errors.Is(d.Error, gorm.ErrRecordNotFound) {
				return result, nil
			}
			return result, d.Error
		}
		belongs = []uint{}
		for _, i := range p {
			belongs = append(belongs, i.ID)
			result = append(result, i.ID)
		}
	}
	return result, nil
}
